var oldCustomerId = '',$quantityTotal=$('#quantityTotal'),$totalPriceTotal=$('#totalPrice'),$cartonTotal=$('#cartonTotal'),$netWeightTotal=$('#netWeightTotal'),$grossWeightTotal=$('#grossWeightTotal');
function generateDocNo() {
    show_loading();
    $.post(rurl('scm/serialNumber/generateDocNo'),{'type':'exp_order'},function (res) {
        if(isSuccess(res)){
            $('#docNo').val(res.data);
        }
    });
}
function fullCustomerData(cus){
    if(oldCustomerId!=cus.id){
        obtainAgreement(cus.id);
        takeDeliveryInformation(cus.name);// 获取客户提货信息
        takeInformation(cus.name);// 获取境外交货送货信息
        $("#supplierName").val("");//清除境外客户
    }
    oldCustomerId = cus.id;
}
function obtainAgreement(customerId,defVal){
    if(isEmpty(customerId)){return;}
    $.post(rurl('scm/expAgreement/getAuditAgreement'),{'customerId':customerId},function (res) {
        if (isSuccess(res)) {
            var data = res.data;
            if (data.length == 0) {
                prompt_warn('当前客户未找到有效协议报价!',function () {
                    $('#customerName').select();
                });
            }else{
                var $agreementId = $('#agreementId'),$declareType = $('#declareType');
                $agreementId.get(0).length = 0;
                $declareType.get(0).length = 0;
                $agreementId.append('<option value="'+data[0].id+'">'+data[0].quoteDescribe+'</option>');
                $declareType.append('<option value="'+data[0].declareType+'">'+data[0].declareTypeDesc+'</option>');
                layui.form.render('select');
            }
        }
    });

}
$('.addrow-btn').click(function () {createRow();});

// 境外送货信息
$('#maintainInformation').click(function () {
    var customerName = $('#customerName').val();
    if(!isEmpty(customerName)){
        var mid=parent.parent.obtainMIdByOperation('customer_list'),taskArg={"documentId":oldCustomerId,"documentClass":"","operation":"customer_edit"};
        if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
        setLocalStorage('TASK_'+mid,JSON.stringify({"name":customerName}));
        setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
        parent.parent.refreshTab(mid);
    }else{
        show_error('请先选择客户');
    }
});
// 国内提货信息维护
$('#maintainDeliveryInformation').click(function () {
    var customerName = $('#customerName').val();
    if(!isEmpty(customerName)){
        var mid=parent.parent.obtainMIdByOperation('customer_list'),taskArg={"documentId":oldCustomerId,"documentClass":"Customer","operation":"customer_edit"};
        if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
        setLocalStorage('TASK_'+mid,JSON.stringify({"name":customerName}));
        setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
        parent.parent.refreshTab(mid);
    }else{
        show_error('请先选择客户');
    }
});
//获取客户收货地址
function takeDeliveryInformation(name,defDiVal){
    var customerName = (name || $('#customerName').val());
    if(!isEmpty(customerName)){
        var deliveryInformationsObj = $('#deliveryInformations');
        deliveryInformationsObj.html('<img src="'+rurl('images/indicator.gif')+'"/>');
        $.post(rurl('scm/customerDeliveryInfo/effectiveList'),{'customerName':customerName},function (res) {
            var thtml = [];
            $.each((res.data || []),function (i,o) {
                if(isEmpty(defDiVal)){defDiVal=o.id;}
                thtml.push('<div class="range-list-item"><input type="radio" name="customerDeliveryInfoId" value="'+o.id+'" title="【'+o.companyName+'】'+o.provinceName+o.cityName+o.areaName+o.address+' ('+o.linkPerson+' '+o.linkTel+')" '+(o.id==defDiVal?'checked="true"':'')+'></div>');
            });
            deliveryInformationsObj.html(thtml.join(""));
            layui.form.render('radio');
        });
    }else{
        show_error('请先选择客户');
    }
}
//获取境外送货地址
function takeInformation(name,defVal){
    var customerName = (name || $('#customerName').val());
    if(!isEmpty(customerName)){
        var takeInformationsObj = $('#takeInformations');
        takeInformationsObj.html('<img src="'+rurl('images/indicator.gif')+'"/>');
        $.post(rurl('scm/customerAbroadDeliveryInfo/effectiveList'),{'customerName':customerName},function (res) {
            var thtml = [];
            $.each((res.data || []),function (i,o) {
                if(isEmpty(defVal)){defVal = o.id;}
                thtml.push('<div class="range-list-item"><input type="radio" name="supplierTakeInfoId" value="'+o.id+'" title="【'+o.companyName+'】'+o.provinceName+o.cityName+o.areaName+o.address+' ('+o.linkPerson+' '+o.linkTel+')" '+(o.id==defVal?'checked="true"':'')+'></div>');
            });
            takeInformationsObj.html(thtml.join(""));
            layui.form.render('radio');
        });
    }else{
        show_error('请先选择客户');
    }
}
function createRows(members) {
    var mhtml = [],tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    $.each(members,function (i,o) {
        mhtml.push(createRowHtml(o.id,o.model,o.name,o.brand,o.unitName,o.quantity,o.unitPrice,o.totalPrice,o.cartonNum,o.netWeight,o.grossWeight,o.goodsCode,o.spec));
        tquantity+=o.quantity;ttotalPrice+=o.totalPrice;tcartonNum+=o.cartonNum;tnetWeight+=o.netWeight;tgrossWeight+=o.grossWeight;
    });
    $('#materialBody').append(mhtml.join(''));
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*10000)/10000);
    $grossWeightTotal.html(Math.round(tgrossWeight*10000)/10000);
    autoAllModelExp();
    //autoAllNameExp();
    //autoAllBrandExp();
    autoUnit();
    initInput();
    createIndex();
}
function createRow(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,netWeight,grossWeight,goodsCode,goodsSpec) {
    if($('.mindex').length==50){show_error('最多添加50条产品信息！');return;}
    $('#materialBody').append(createRowHtml(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,netWeight,grossWeight,goodsCode,goodsSpec));
    autoAllModelExp();
    //autoAllNameExp();
    //autoAllBrandExp();
    autoUnit();
    initInput();
    createIndex();
    $('.tabBody').scrollTop(10000);
}
function createRowHtml(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,netWeight,grossWeight,goodsCode,goodsSpec) {
    return [
        '<tr><td class="t-a-c mindex"></td>',
        '<td><input type="text" name="name" LIST class="layui-input required auto-customer-name-exp" value="'+(isEmpty(goodsName)?'':goodsName)+'" placeholder="品名"/></td>',
        '<td><input type="hidden" name="id" LIST value="'+(isEmpty(mid)?'':mid)+'"/><input type="text" name="model" LIST class="layui-input required auto-customer-model-exp" placeholder="型号" value="'+(isEmpty(goodsModel)?'':goodsModel)+'"/></td>',
        '<td><input type="text" name="brand" LIST class="layui-input required auto-customer-brand-exp" placeholder="品牌" value="'+(isEmpty(goodsBrand)?'':goodsBrand)+'"/></td>',
        '<td><input type="text" name="goodsCode" LIST class="layui-input" placeholder="物料编号" value="'+(isEmpty(goodsCode)?'':goodsCode)+'"/></td>',
        '<td><input type="text" name="unitName" LIST class="layui-input auto-unit required" value="'+(isEmpty(unitName)?'个':unitName)+'"/></td>',
        '<td><input type="text" name="quantity" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(quantity)?'':quantity)+'"/></td>',
        '<td><input type="text" name="unitPrice" LIST class="layui-input layui-disabled" readonly value="'+(isEmpty(unitPrice)?'0.0000':unitPrice)+'"/></td>',
        '<td><input type="text" name="totalPrice" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(totalPrice)?'':totalPrice)+'"/></td>',
        '<td><input type="text" name="cartonNum" LIST onblur="calculationAll()" INT class="layui-input required" value="'+(isEmpty(cartonNum)?'0':cartonNum)+'"/></td>',
        '<td><input type="text" name="netWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(netWeight)?'0.0000':netWeight)+'"/></td>',
        '<td><input type="text" name="grossWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(grossWeight)?'0.0000':grossWeight)+'"/></td>',
        '<td><input type="text" name="spec" LIST class="layui-input required" value="'+(isEmpty(goodsSpec)?'':goodsSpec)+'"/></td>',
        '<td class="t-a-c"><a href="javascript:" onclick="deleteRow(this)"><i class="fa fa-trash-o"></i></a></td></tr>'
    ].join('');
}
function fullCustomerModelDataExp(e,data) {
    var $per = $(e).parent().parent();
    $per.find('input[name="name"]').val(data.name);
    $per.find('input[name="brand"]').val(data.brand);
    $per.find('input[name="spec"]').val(data.spec);
}
function fullCustomerNameDataExp(e,data) {
    var $per = $(e).parent().parent();
    $per.find('input[name="model"]').val(data.model);
    $per.find('input[name="brand"]').val(data.brand);
    $per.find('input[name="spec"]').val(data.spec);
}
function fullCustomerBrandDataExp(e,data){
    var $per = $(e).parent().parent();
    $per.find('input[name="model"]').val(data.model);
    $per.find('input[name="name"]').val(data.name);
    $per.find('input[name="spec"]').val(data.spec);
}
function createIndex() {
    var mind = 1;
    $.each($('.mindex'),function (i,o) {
        $(o).html(mind++);
    });
}
function deleteRow(e) {
    var $per = $(e).parent().parent();
    $per.remove();
    createIndex();
    calculationAll();
}
function showOrHide(e) {
    $.each(e,function (i,o) {
        var $that = $(o);
        var $mark = $('[mark="'+$that.attr('id')+'"]');
        $mark.hide();
        $.each($mark,function (j,k) {
            var zmkeys = $(k).attr('zm-key').split(",");
            if(contain(zmkeys,$that.val())){
                $(k).show();
            }
        });
    });
}
function calculationAll(e) {
    var tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    if(!isEmpty(e)){
        var $that = $(e),$parent=$that.parent().parent(),$quantity=$parent.find('input[name="quantity"]'),$unitPrice=$parent.find('input[name="unitPrice"]'),$totalPrice=$parent.find('input[name="totalPrice"]');
        switch ($that.attr('name')){
            case 'quantity':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
            case 'unitPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var unitPrice = Math.round(parseFloat($unitPrice.val() || '0.0')*10000)/10000;
                $totalPrice.val(Math.round(quantity*unitPrice*100)/100);
                break;
            case 'totalPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                if(quantity==0.0){$unitPrice.val('0.0000');return;}
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
        }
    }
    $.each($('#materialBody').find('tr'),function (i,o) {
        var $that = $(o);
        tquantity += Math.round(parseFloat($that.find('input[name="quantity"]').val() || '0.0')*100)/100;
        ttotalPrice += Math.round(parseFloat($that.find('input[name="totalPrice"]').val() || '0.0')*100)/100;
        tcartonNum += parseInt($that.find('input[name="cartonNum"]').val() || '0');
        tnetWeight += Math.round(parseFloat($that.find('input[name="netWeight"]').val() || '0.0')*10000)/10000;
        tgrossWeight += Math.round(parseFloat($that.find('input[name="grossWeight"]').val() || '0.0')*10000)/10000;
    });
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*10000)/10000);
    $grossWeightTotal.html(Math.round(tgrossWeight*10000)/10000);
}
function initOverseasDelivery(){
    var logistics = $('#orderLogisticsForm').serializeJson();
    if(logistics.isCharterCar == 'true'){
        $('#charter').show();
    }else{
        $('#charter').hide();
    }
    if(logistics.deliveryDestination == 'destination'){
        $('#destination').show();
    }else{
        $('#destination').hide();
    }
}
function initBuyerType(){
    var order = $('#orderMainForm').serializeJson();
    if(order.subjectOverseasType == '1'){
        $('#self_subjectOverseas').show();
        $('#customer_subjectOverseas').hide();
        $('#overseas_supplierName').show();
    }else{
        $('#self_subjectOverseas').hide();
        $('#customer_subjectOverseas').show();
        $('#overseas_supplierName').hide();
    }
}
//订单明细
function obtainMenberJSON() {
    var members = [],orderMember = $('#orderMemberForm').serializeJson(),keys=[];
    for(var key in orderMember){keys.push(key);}
    $.each(orderMember[keys[0]] ||[],function (i,o) {
        var item = {};
        $.each(keys,function (j,k) {
            item[k] = orderMember[k][i];
        });
        members.push(item);
    });
    return members;
}
var auto1 = {
    "districtCodeName": {hid: 'districtCode',type:'CUS_DISTRICT',dropUp:true},
},auto2 = {
    "cusTradeCountryName": {hid: 'cusTradeCountry',type:'CUS_MAPPING_COUNTRY_CODE_V'},
    "cusTradeNationCodeName": {hid: 'cusTradeNationCode',type:'CUS_MAPPING_COUNTRY_CODE_V'},
    "distinatePortName": {hid: 'distinatePort',type:'CUS_MAPPING_PORT_CODE_V',style:'min-width:300px'},

}
function initAuto1(data){
    $.each(auto1,function (key,val) {
        var $input = $('#'+key);
        if($input.length>0){
            var source = [];
            $.each(data[val.type]||[],function (i,o) {
                source.push({'label':o.c+'-'+o.n,'value':o.n});
            });
            if(source.length>0){
                $input.autocompleter({
                    source:source,
                    style:removeNull(val.style),
                    limit:20,
                    focusOpen:(val.focusOpen),
                    hiddenId:val.hid,
                    dropUp:val.dropUp,
                    callback:val.callback
                });
            }
        }
    });
}
function initAuto2(data){
    $.each(auto2,function (key,val) {
        var $input = $('#'+key);
        if($input.length>0){
            var source = [];
            $.each(data[val.type]||[],function (i,o) {
                o['label'] = o.c+'_'+o.n+'_'+o.o+'_'+o.q;
                source.push(o);
            });
            if(source.length>0){
                $input.autocompleter({
                    source:source,
                    style:removeNull(val.style),
                    limit:20,
                    focusOpen:(val.focusOpen),
                    hiddenId:val.hid,
                    dropUp:val.dropUp,
                    callback:val.callback,
                    template:'<div>{{c}}-{{n}} <span class="fr">{{o}}&nbsp;&nbsp;{{q}}</span></div>'
                });
            }
        }
    });
}
function initBaseData(){
    var declDatas1 = localStorage.getItem("static_decl_datas1");
    if(isEmpty(declDatas1)){
        $.post(rurl('system/customsData/formatData1'),{},function (res) {
            if(isSuccessWarn(res)){
                localStorage.setItem("static_decl_datas1",JSON.stringify(res.data));
                initAuto1(res.data);
            }
        });
    }else{
        initAuto1(JSON.parse(declDatas1));
    }
    var declDatas2 = localStorage.getItem("static_decl_datas2");
    if(isEmpty(declDatas2)){
        $.post(rurl('system/customsData/formatData2'),{},function (res) {
            if(isSuccessWarn(res)){
                localStorage.setItem("static_decl_datas2",JSON.stringify(res.data));
                initAuto2(res.data);
            }
        });
    }else{
        initAuto2(JSON.parse(declDatas2));
    }
}
$(function () {
    $.get(rurl('system/version'),{},function (res) {
        if(isSuccess(res)){
            if(res.data != localStorage.getItem('static_version')){
                localStorage.setItem("static_code_datas","");
                localStorage.setItem("static_decl_datas1","");
                localStorage.setItem("static_decl_datas2","");
                localStorage.setItem("static_prod_traf_data","");
                localStorage.setItem("static_version",res.data);
            }
            initBaseData();
        }
    });
});
